<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * @author petra.barus
 */
class Sandbox {
    public static function execute($parameter, $command, &$output, &$retval = NULL)
    {
        $output = "";
        $execoutput = array();
        $moeval_path = Kohana::config('evaluator.moevalbox_path');
        $exec = $moeval_path." ".$parameter." -- ".$command;
        //echo "--------------------------\n";
        //echo "$exec\n";
        //return;
        $executelastline = exec($exec." 2>&1", $execoutput, $retval);
        echo "$executelastline\n";
        $execoutput = implode("\n", $execoutput);
        if (strpos($executelastline, "Time limit exceeded") !== false)
        {
            throw new SandboxException(SandboxException::ERR_TIMELIMIT_EXCEEDED);
        }
        if (strpos($executelastline, "Forbidden syscall") !== false)
        {
            throw new SandboxException(SandboxException::ERR_FORBIDDEN_SYSCALL);
        }
        if (strpos($executelastline, "File access forbidden") !== false)
        {
            throw new SandboxException(SandboxException::ERR_FORBIDDEN_ACCESS);
        }
        if (strpos(strtolower($execoutput), "Out of memory") !== false)
        {
            throw new SandboxException(SandboxException::ERR_TIMELIMIT_EXCEEDED);
        }        if (strpos($execoutput, "Out of memory") !== false)
        {
            throw new SandboxException(SandboxException::ERR_TIMELIMIT_EXCEEDED);
        }
        if (strpos($execoutput, "virtual memory exhausted") !== false)
        {
            throw new SandboxException(SandboxException::ERR_TIMELIMIT_EXCEEDED);
        }
        $output = $execoutput;
        return $retval;
    }

    public static function get_temp_name($prefix = NULL)
    {
        $tempdir = Kohana::config('evaluator.sandbox_temp_dir');
        $prefix = (!is_null($prefix)) ? $prefix : '';
        $path = tempnam($tempdir, $prefix);
        return $path;
    }
}
//end of file